#!/usr/bin/env python3

import os
import sys
from pathlib import Path
import argparse
import re

# Add the parent directory to the path so we can import the package
sys.path.append(str(Path(__file__).parent.parent))

from cpp_flow_map.Tools.CppCodeParser import CppCodeParser

def test_parser(source_dir, target_file):
    """Test the enhanced parser on a specific file"""
    print(f"Testing enhanced parser on {target_file} in {source_dir}")
    
    # Initialize the parser
    parser = CppCodeParser([source_dir])
    parser.debug_mode = True  # Enable debug output
    
    # Parse all files
    parser.parse_all_files()
    
    # Get the basename of the target file (without extension)
    if target_file.endswith(('.c', '.cpp', '.cxx', '.cc', '.h', '.hpp')):
        target_basename = target_file[:target_file.rfind('.')]
    else:
        target_basename = target_file
    
    # Extract just the filename without directory path
    target_basename = os.path.basename(target_basename)
    
    print(f"\nTarget file: {target_basename}")
    
    # Print all functions found in the target file
    if target_basename in parser.compilation_units:
        functions = parser.compilation_units[target_basename]
        print(f"\nFunctions in {target_basename}:")
        for i, func_name in enumerate(functions, 1):
            print(f"{i:3d}. {func_name}")
            
            # Get calls made by this function
            if func_name in parser.functions:
                func = parser.functions[func_name]
                if func.calls:
                    print(f"     Calls {len(func.calls)} functions:")
                    for j, called_func in enumerate(func.calls, 1):
                        print(f"       {j:3d}. {called_func.full_name}")
    else:
        print(f"No functions found in {target_basename}")
    
    # Print entry points
    print("\nEntry points:")
    for i, entry_point in enumerate(parser.entry_points, 1):
        print(f"{i:3d}. {entry_point}")
    
    # Print all compilation units
    print("\nAll compilation units:")
    for unit_name, functions in parser.compilation_units.items():
        print(f"- {unit_name}: {len(functions)} functions")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Test the enhanced C++ parser")
    parser.add_argument('--src', default='./src', help='Source directory')
    parser.add_argument('--target', default='test_multi_cavity_matrix.cpp', help='Target file')
    
    args = parser.parse_args()
    
    test_parser(args.src, args.target) 